home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Objects / object.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-10  |  23.0 KB  |  1,110 lines

  1. /* Generic object operations; and implementation of None (NoObject) */
  2.  
  3. #include "Python.h"
  4.  
  5. /* just for trashcan: */
  6. #include "compile.h"
  7. #include "frameobject.h"
  8. #include "traceback.h"
  9. #include "protos/object.h"
  10.  
  11. #if defined( Py_TRACE_REFS ) || defined( Py_REF_DEBUG )
  12. DL_IMPORT(long) _Py_RefTotal;
  13. #endif
  14.  
  15. /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
  16.    These are used by the individual routines for object creation.
  17.    Do not call them otherwise, they do not initialize the object! */
  18.  
  19. #ifdef COUNT_ALLOCS
  20. static PyTypeObject *type_list;
  21. extern int tuple_zero_allocs, fast_tuple_allocs;
  22. extern int quick_int_allocs, quick_neg_int_allocs;
  23. extern int null_strings, one_strings;
  24. void
  25. dump_counts()
  26. {
  27.     PyTypeObject *tp;
  28.  
  29.     for (tp = type_list; tp; tp = tp->tp_next)
  30.         fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
  31.             tp->tp_name, tp->tp_alloc, tp->tp_free,
  32.             tp->tp_maxalloc);
  33.     fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
  34.         fast_tuple_allocs, tuple_zero_allocs);
  35.     fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
  36.         quick_int_allocs, quick_neg_int_allocs);
  37.     fprintf(stderr, "null strings: %d, 1-strings: %d\n",
  38.         null_strings, one_strings);
  39. }
  40.  
  41. PyObject *
  42. get_counts()
  43. {
  44.     PyTypeObject *tp;
  45.     PyObject *result;
  46.     PyObject *v;
  47.  
  48.     result = PyList_New(0);
  49.     if (result == NULL)
  50.         return NULL;
  51.     for (tp = type_list; tp; tp = tp->tp_next) {
  52.         v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_alloc,
  53.                   tp->tp_free, tp->tp_maxalloc);
  54.         if (v == NULL) {
  55.             Py_DECREF(result);
  56.             return NULL;
  57.         }
  58.         if (PyList_Append(result, v) < 0) {
  59.             Py_DECREF(v);
  60.             Py_DECREF(result);
  61.             return NULL;
  62.         }
  63.         Py_DECREF(v);
  64.     }
  65.     return result;
  66. }
  67.  
  68. void
  69. inc_count(tp)
  70.     PyTypeObject *tp;
  71. {
  72.     if (tp->tp_alloc == 0) {
  73.         /* first time; insert in linked list */
  74.         if (tp->tp_next != NULL) /* sanity check */
  75.             Py_FatalError("XXX inc_count sanity check");
  76.         tp->tp_next = type_list;
  77.         type_list = tp;
  78.     }
  79.     tp->tp_alloc++;
  80.     if (tp->tp_alloc - tp->tp_free > tp->tp_maxalloc)
  81.         tp->tp_maxalloc = tp->tp_alloc - tp->tp_free;
  82. }
  83. #endif
  84.  
  85. PyObject *
  86. PyObject_Init(op, tp)
  87.     PyObject *op;
  88.     PyTypeObject *tp;
  89. {
  90.     if (op == NULL) {
  91.         PyErr_SetString(PyExc_SystemError,
  92.                 "NULL object passed to PyObject_Init");
  93.         return op;
  94.       }
  95.     /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
  96.     op->ob_type = tp;
  97.     _Py_NewReference(op);
  98.     return op;
  99. }
  100.  
  101. PyVarObject *
  102. PyObject_InitVar(op, tp, size)
  103.     PyVarObject *op;
  104.     PyTypeObject *tp;
  105.     int size;
  106. {
  107.     if (op == NULL) {
  108.         PyErr_SetString(PyExc_SystemError,
  109.                 "NULL object passed to PyObject_InitVar");
  110.         return op;
  111.     }
  112.     /* Any changes should be reflected in PyObject_INIT_VAR */
  113.     op->ob_size = size;
  114.     op->ob_type = tp;
  115.     _Py_NewReference((PyObject *)op);
  116.     return op;
  117. }
  118.  
  119. PyObject *
  120. _PyObject_New(tp)
  121.     PyTypeObject *tp;
  122. {
  123.     PyObject *op;
  124.     op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
  125.     if (op == NULL)
  126.         return PyErr_NoMemory();
  127.     return PyObject_INIT(op, tp);
  128. }
  129.  
  130. PyVarObject *
  131. _PyObject_NewVar(tp, size)
  132.     PyTypeObject *tp;
  133.     int size;
  134. {
  135.     PyVarObject *op;
  136.     op = (PyVarObject *) PyObject_MALLOC(_PyObject_VAR_SIZE(tp, size));
  137.     if (op == NULL)
  138.         return (PyVarObject *)PyErr_NoMemory();
  139.     return PyObject_INIT_VAR(op, tp, size);
  140. }
  141.  
  142. void
  143. _PyObject_Del(op)
  144.     PyObject *op;
  145. {
  146.     PyObject_FREE(op);
  147. }
  148.  
  149. int
  150. PyObject_Print(op, fp, flags)
  151.     PyObject *op;
  152.     FILE *fp;
  153.     int flags;
  154. {
  155.     int ret = 0;
  156.     if (PyErr_CheckSignals())
  157.         return -1;
  158. #ifdef USE_STACKCHECK
  159.     if (PyOS_CheckStack()) {
  160.         PyErr_SetString(PyExc_MemoryError, "Stack overflow");
  161.         return -1;
  162.     }
  163. #endif
  164.     clearerr(fp); /* Clear any previous error condition */
  165.     if (op == NULL) {
  166.         fprintf(fp, "<nil>");
  167.     }
  168.     else {
  169.         if (op->ob_refcnt <= 0)
  170.             fprintf(fp, "<refcnt %u at %lx>",
  171.                 op->ob_refcnt, (long)op);
  172.         else if (op->ob_type->tp_print == NULL) {
  173.             if (op->ob_type->tp_repr == NULL) {
  174.                 fprintf(fp, "<%s object at %lx>",
  175.                     op->ob_type->tp_name, (long)op);
  176.             }
  177.             else {
  178.                 PyObject *s;
  179.                 if (flags & Py_PRINT_RAW)
  180.                     s = PyObject_Str(op);
  181.                 else
  182.                     s = PyObject_Repr(op);
  183.                 if (s == NULL)
  184.                     ret = -1;
  185.                 else {
  186.                     ret = PyObject_Print(s, fp,
  187.                                  Py_PRINT_RAW);
  188.                 }
  189.                 Py_XDECREF(s);
  190.             }
  191.         }
  192.         else
  193.             ret = (*op->ob_type->tp_print)(op, fp, flags);
  194.     }
  195.     if (ret == 0) {
  196.         if (ferror(fp)) {
  197.             PyErr_SetFromErrno(PyExc_IOError);
  198.             clearerr(fp);
  199.             ret = -1;
  200.         }
  201.     }
  202.     return ret;
  203. }
  204.  
  205. PyObject *
  206. PyObject_Repr(v)
  207.     PyObject *v;
  208. {
  209.     if (PyErr_CheckSignals())
  210.         return NULL;
  211. #ifdef USE_STACKCHECK
  212.     if (PyOS_CheckStack()) {
  213.         PyErr_SetString(PyExc_MemoryError, "Stack overflow");
  214.         return NULL;
  215.     }
  216. #endif
  217.     if (v == NULL)
  218.         return PyString_FromString("<NULL>");
  219.     else if (v->ob_type->tp_repr == NULL) {
  220.         char buf[120];
  221.         sprintf(buf, "<%.80s object at %lx>",
  222.             v->ob_type->tp_name, (long)v);
  223.         return PyString_FromString(buf);
  224.     }
  225.     else {
  226.         PyObject *res;
  227.         res = (*v->ob_type->tp_repr)(v);
  228.         if (res == NULL)
  229.             return NULL;
  230.         if (PyUnicode_Check(res)) {
  231.             PyObject* str;
  232.             str = PyUnicode_AsEncodedString(res, NULL, NULL);
  233.             if (str) {
  234.                 Py_DECREF(res);
  235.                 res = str;
  236.             }
  237.         }
  238.         if (!PyString_Check(res)) {
  239.             PyErr_Format(PyExc_TypeError,
  240.                      "__repr__ returned non-string (type %.200s)",
  241.                      res->ob_type->tp_name);
  242.             Py_DECREF(res);
  243.             return NULL;
  244.         }
  245.         return res;
  246.     }
  247. }
  248.  
  249. PyObject *
  250. PyObject_Str(v)
  251.     PyObject *v;
  252. {
  253.     PyObject *res;
  254.     
  255.     if (v == NULL)
  256.         return PyString_FromString("<NULL>");
  257.     else if (PyString_Check(v)) {
  258.         Py_INCREF(v);
  259.         return v;
  260.     }
  261.     else if (v->ob_type->tp_str != NULL)
  262.         res = (*v->ob_type->tp_str)(v);
  263.     else {
  264.         PyObject *func;
  265.         if (!PyInstance_Check(v) ||
  266.             (func = PyObject_GetAttrString(v, "__str__")) == NULL) {
  267.             PyErr_Clear();
  268.             return PyObject_Repr(v);
  269.         }
  270.         res = PyEval_CallObject(func, (PyObject *)NULL);
  271.         Py_DECREF(func);
  272.     }
  273.     if (res == NULL)
  274.         return NULL;
  275.     if (PyUnicode_Check(res)) {
  276.         PyObject* str;
  277.         str = PyUnicode_AsEncodedString(res, NULL, NULL);
  278.         if (str) {
  279.             Py_DECREF(res);
  280.             res = str;
  281.         }
  282.     }
  283.     if (!PyString_Check(res)) {
  284.         PyErr_Format(PyExc_TypeError,
  285.                  "__str__ returned non-string (type %.200s)",
  286.                  res->ob_type->tp_name);
  287.         Py_DECREF(res);
  288.         return NULL;
  289.     }
  290.     return res;
  291. }
  292.  
  293. static PyObject *
  294. do_cmp(v, w)
  295.     PyObject *v, *w;
  296. {
  297.     long c;
  298.     /* __rcmp__ actually won't be called unless __cmp__ isn't defined,
  299.        because the check in cmpobject() reverses the objects first.
  300.        This is intentional -- it makes no sense to define cmp(x,y)
  301.        different than -cmp(y,x). */
  302.     if (PyInstance_Check(v) || PyInstance_Check(w))
  303.         return PyInstance_DoBinOp(v, w, "__cmp__", "__rcmp__", do_cmp);
  304.     c = PyObject_Compare(v, w);
  305.     if (c && PyErr_Occurred())
  306.         return NULL;
  307.     return PyInt_FromLong(c);
  308. }
  309.  
  310. PyObject *_PyCompareState_Key;
  311.  
  312. /* _PyCompareState_nesting is incremented beforing call compare (for
  313.    some types) and decremented on exit.  If the count exceeds the
  314.    nesting limit, enable code to detect circular data structures.
  315. */
  316. #define NESTING_LIMIT 500
  317. int _PyCompareState_nesting = 0;
  318.  
  319. static PyObject*
  320. get_inprogress_dict()
  321. {
  322.     PyObject *tstate_dict, *inprogress;
  323.  
  324.     tstate_dict = PyThreadState_GetDict();
  325.     if (tstate_dict == NULL) {
  326.         PyErr_BadInternalCall();
  327.         return NULL;
  328.     } 
  329.     inprogress = PyDict_GetItem(tstate_dict, _PyCompareState_Key); 
  330.     if (inprogress == NULL) {
  331.         inprogress = PyDict_New();
  332.         if (inprogress == NULL)
  333.             return NULL;
  334.         if (PyDict_SetItem(tstate_dict, _PyCompareState_Key,
  335.                    inprogress) == -1) {
  336.             Py_DECREF(inprogress);
  337.             return NULL;
  338.         }
  339.         Py_DECREF(inprogress);
  340.     }
  341.     return inprogress;
  342. }
  343.  
  344. static PyObject *
  345. make_pair(v, w)
  346.     PyObject *v, *w;
  347. {
  348.     PyObject *pair;
  349.  
  350.     pair = PyTuple_New(2);
  351.     if (pair == NULL) {
  352.         return NULL;
  353.     }
  354.     if ((long)v <= (long)w) {
  355.         PyTuple_SET_ITEM(pair, 0, PyLong_FromVoidPtr((void *)v));
  356.         PyTuple_SET_ITEM(pair, 1, PyLong_FromVoidPtr((void *)w));
  357.     } else {
  358.         PyTuple_SET_ITEM(pair, 0, PyLong_FromVoidPtr((void *)w));
  359.         PyTuple_SET_ITEM(pair, 1, PyLong_FromVoidPtr((void *)v));
  360.     }
  361.     return pair;
  362. }
  363.  
  364. int
  365. PyObject_Compare(v, w)
  366.     PyObject *v, *w;
  367. {
  368.     PyTypeObject *vtp, *wtp;
  369.     int result;
  370.  
  371.     if (v == NULL || w == NULL) {
  372.         PyErr_BadInternalCall();
  373.         return -1;
  374.     }
  375.     if (v == w)
  376.         return 0;
  377.     if (PyInstance_Check(v) || PyInstance_Check(w)) {
  378.         PyObject *res;
  379.         int c;
  380.         if (!PyInstance_Check(v))
  381.             return -PyObject_Compare(w, v);
  382.         if (++_PyCompareState_nesting > NESTING_LIMIT) {
  383.             PyObject *inprogress, *pair;
  384.  
  385.             inprogress = get_inprogress_dict();
  386.             if (inprogress == NULL) {
  387.                 return -1;
  388.             }
  389.             pair = make_pair(v, w);
  390.             if (PyDict_GetItem(inprogress, pair)) {
  391.                 /* already comparing these objects.  assume
  392.                    they're equal until shown otherwise */
  393.                 Py_DECREF(pair);
  394.                 --_PyCompareState_nesting;
  395.                 return 0;
  396.             }
  397.             if (PyDict_SetItem(inprogress, pair, pair) == -1) {
  398.                 return -1;
  399.             }
  400.             res = do_cmp(v, w);
  401.             _PyCompareState_nesting--;
  402.             /* XXX DelItem shouldn't fail */
  403.             PyDict_DelItem(inprogress, pair);
  404.             Py_DECREF(pair);
  405.         } else {
  406.             res = do_cmp(v, w);
  407.         }
  408.         if (res == NULL)
  409.             return -1;
  410.         if (!PyInt_Check(res)) {
  411.             Py_DECREF(res);
  412.             PyErr_SetString(PyExc_TypeError,
  413.                     "comparison did not return an int");
  414.             return -1;
  415.         }
  416.         c = PyInt_AsLong(res);
  417.         Py_DECREF(res);
  418.         return (c < 0) ? -1 : (c > 0) ? 1 : 0;    
  419.     }
  420.     if ((vtp = v->ob_type) != (wtp = w->ob_type)) {
  421.         char *vname = vtp->tp_name;
  422.         char *wname = wtp->tp_name;
  423.         if (vtp->tp_as_number != NULL && wtp->tp_as_number != NULL) {
  424.             int err;
  425.             err = PyNumber_CoerceEx(&v, &w);
  426.             if (err < 0)
  427.                 return -1;
  428.             else if (err == 0) {
  429.                 int cmp;
  430.                 vtp = v->ob_type;
  431.                 if (vtp->tp_compare == NULL)
  432.                     cmp = (v < w) ? -1 : 1;
  433.                 else
  434.                     cmp = (*vtp->tp_compare)(v, w);
  435.                 Py_DECREF(v);
  436.                 Py_DECREF(w);
  437.                 return cmp;
  438.             }
  439.         }
  440.         else if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
  441.             int result = PyUnicode_Compare(v, w);
  442.             if (result == -1 && PyErr_Occurred() && 
  443.                 PyErr_ExceptionMatches(PyExc_TypeError))
  444.                 /* TypeErrors are ignored: if Unicode coercion
  445.                 fails due to one of the arguments not
  446.                  having the right type, we continue as
  447.                 defined by the coercion protocol (see
  448.                 above). Luckily, decoding errors are
  449.                 reported as ValueErrors and are not masked
  450.                 by this technique. */
  451.                 PyErr_Clear();
  452.             else
  453.                 return result;
  454.         }
  455.         else if (vtp->tp_as_number != NULL)
  456.             vname = "";
  457.         else if (wtp->tp_as_number != NULL)
  458.             wname = "";
  459.         /* Numerical types compare smaller than all other types */
  460.         return strcmp(vname, wname);
  461.     }
  462.     if (vtp->tp_compare == NULL) {
  463.         return (v < w) ? -1 : 1;
  464.     }
  465.     if (++_PyCompareState_nesting > NESTING_LIMIT
  466.         && (vtp->tp_as_mapping 
  467.         || (vtp->tp_as_sequence && !PyString_Check(v)))) {
  468.         PyObject *inprogress, *pair;
  469.  
  470.         inprogress = get_inprogress_dict();
  471.         if (inprogress == NULL) {
  472.             return -1;
  473.         }
  474.         pair = make_pair(v, w);
  475.         if (PyDict_GetItem(inprogress, pair)) {
  476.             /* already comparing these objects.  assume
  477.                they're equal until shown otherwise */
  478.             _PyCompareState_nesting--;
  479.             Py_DECREF(pair);
  480.             return 0;
  481.         }
  482.         if (PyDict_SetItem(inprogress, pair, pair) == -1) {
  483.             return -1;
  484.         }
  485.         result = (*vtp->tp_compare)(v, w);
  486.         _PyCompareState_nesting--;
  487.         PyDict_DelItem(inprogress, pair); /* XXX shouldn't fail */
  488.         Py_DECREF(pair);
  489.     } else {
  490.         result = (*vtp->tp_compare)(v, w);
  491.     }
  492.     return result;
  493. }
  494.  
  495. long
  496. PyObject_Hash(v)
  497.     PyObject *v;
  498. {
  499.     PyTypeObject *tp = v->ob_type;
  500.     if (tp->tp_hash != NULL)
  501.         return (*tp->tp_hash)(v);
  502.     if (tp->tp_compare == NULL)
  503.         return (long) v; /* Use address as hash value */
  504.     /* If there's a cmp but no hash defined, the object can't be hashed */
  505.     PyErr_SetString(PyExc_TypeError, "unhashable type");
  506.     return -1;
  507. }
  508.  
  509. PyObject *
  510. PyObject_GetAttrString(v, name)
  511.     PyObject *v;
  512.     char *name;
  513. {
  514.     if (v->ob_type->tp_getattro != NULL) {
  515.         PyObject *w, *res;
  516.         w = PyString_InternFromString(name);
  517.         if (w == NULL)
  518.             return NULL;
  519.         res = (*v->ob_type->tp_getattro)(v, w);
  520.         Py_XDECREF(w);
  521.         return res;
  522.     }
  523.  
  524.     if (v->ob_type->tp_getattr == NULL) {
  525.         PyErr_Format(PyExc_AttributeError,
  526.                  "'%.50s' object has no attribute '%.400s'",
  527.                  v->ob_type->tp_name,
  528.                  name);
  529.         return NULL;
  530.     }
  531.     else {
  532.         return (*v->ob_type->tp_getattr)(v, name);
  533.     }
  534. }
  535.  
  536. int
  537. PyObject_HasAttrString(v, name)
  538.     PyObject *v;
  539.     char *name;
  540. {
  541.     PyObject *res = PyObject_GetAttrString(v, name);
  542.     if (res != NULL) {
  543.         Py_DECREF(res);
  544.         return 1;
  545.     }
  546.     PyErr_Clear();
  547.     return 0;
  548. }
  549.  
  550. int
  551. PyObject_SetAttrString(v, name, w)
  552.     PyObject *v;
  553.     char *name;
  554.     PyObject *w;
  555. {
  556.     if (v->ob_type->tp_setattro != NULL) {
  557.         PyObject *s;
  558.         int res;
  559.         s = PyString_InternFromString(name);
  560.         if (s == NULL)
  561.             return -1;
  562.         res = (*v->ob_type->tp_setattro)(v, s, w);
  563.         Py_XDECREF(s);
  564.         return res;
  565.     }
  566.  
  567.     if (v->ob_type->tp_setattr == NULL) {
  568.         if (v->ob_type->tp_getattr == NULL)
  569.             PyErr_SetString(PyExc_TypeError,
  570.                    "attribute-less object (assign or del)");
  571.         else
  572.             PyErr_SetString(PyExc_TypeError,
  573.                    "object has read-only attributes");
  574.         return -1;
  575.     }
  576.     else {
  577.         return (*v->ob_type->tp_setattr)(v, name, w);
  578.     }
  579. }
  580.  
  581. PyObject *
  582. PyObject_GetAttr(v, name)
  583.     PyObject *v;
  584.     PyObject *name;
  585. {
  586.     if (v->ob_type->tp_getattro != NULL)
  587.         return (*v->ob_type->tp_getattro)(v, name);
  588.     else
  589.         return PyObject_GetAttrString(v, PyString_AsString(name));
  590. }
  591.  
  592. int
  593. PyObject_HasAttr(v, name)
  594.     PyObject *v;
  595.     PyObject *name;
  596. {
  597.     PyObject *res = PyObject_GetAttr(v, name);
  598.     if (res != NULL) {
  599.         Py_DECREF(res);
  600.         return 1;
  601.     }
  602.     PyErr_Clear();
  603.     return 0;
  604. }
  605.  
  606. int
  607. PyObject_SetAttr(v, name, value)
  608.     PyObject *v;
  609.     PyObject *name;
  610.     PyObject *value;
  611. {
  612.     int err;
  613.     Py_INCREF(name);
  614.     PyString_InternInPlace(&name);
  615.     if (v->ob_type->tp_setattro != NULL)
  616.         err = (*v->ob_type->tp_setattro)(v, name, value);
  617.     else
  618.         err = PyObject_SetAttrString(
  619.             v, PyString_AsString(name), value);
  620.     Py_DECREF(name);
  621.     return err;
  622. }
  623.  
  624. /* Test a value used as condition, e.g., in a for or if statement.
  625.    Return -1 if an error occurred */
  626.  
  627. int
  628. PyObject_IsTrue(v)
  629.     PyObject *v;
  630. {
  631.     int res;
  632.     if (v == Py_None)
  633.         res = 0;
  634.     else if (v->ob_type->tp_as_number != NULL &&
  635.          v->ob_type->tp_as_number->nb_nonzero != NULL)
  636.         res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
  637.     else if (v->ob_type->tp_as_mapping != NULL &&
  638.          v->ob_type->tp_as_mapping->mp_length != NULL)
  639.         res = (*v->ob_type->tp_as_mapping->mp_length)(v);
  640.     else if (v->ob_type->tp_as_sequence != NULL &&
  641.          v->ob_type->tp_as_sequence->sq_length != NULL)
  642.         res = (*v->ob_type->tp_as_sequence->sq_length)(v);
  643.     else
  644.         res = 1;
  645.     if (res > 0)
  646.         res = 1;
  647.     return res;
  648. }
  649.  
  650. /* equivalent of 'not v' 
  651.    Return -1 if an error occurred */
  652.  
  653. int
  654. PyObject_Not(v)
  655.     PyObject *v;
  656. {
  657.     int res;
  658.     res = PyObject_IsTrue(v);
  659.     if (res < 0)
  660.         return res;
  661.     return res == 0;
  662. }
  663.  
  664. /* Coerce two numeric types to the "larger" one.
  665.    Increment the reference count on each argument.
  666.    Return -1 and raise an exception if no coercion is possible
  667.    (and then no reference count is incremented).
  668. */
  669.  
  670. int
  671. PyNumber_CoerceEx(pv, pw)
  672.     PyObject **pv, **pw;
  673. {
  674.     register PyObject *v = *pv;
  675.     register PyObject *w = *pw;
  676.     int res;
  677.  
  678.     if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
  679.         Py_INCREF(v);
  680.         Py_INCREF(w);
  681.         return 0;
  682.     }
  683.     if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
  684.         res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
  685.         if (res <= 0)
  686.             return res;
  687.     }
  688.     if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
  689.         res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
  690.         if (res <= 0)
  691.             return res;
  692.     }
  693.     return 1;
  694. }
  695.  
  696. int
  697. PyNumber_Coerce(pv, pw)
  698.     PyObject **pv, **pw;
  699. {
  700.     int err = PyNumber_CoerceEx(pv, pw);
  701.     if (err <= 0)
  702.         return err;
  703.     PyErr_SetString(PyExc_TypeError, "number coercion failed");
  704.     return -1;
  705. }
  706.  
  707.  
  708. /* Test whether an object can be called */
  709.  
  710. int
  711. PyCallable_Check(x)
  712.     PyObject *x;
  713. {
  714.     if (x == NULL)
  715.         return 0;
  716.     if (x->ob_type->tp_call != NULL ||
  717.         PyFunction_Check(x) ||
  718.         PyMethod_Check(x) ||
  719.         PyCFunction_Check(x) ||
  720.         PyClass_Check(x))
  721.         return 1;
  722.     if (PyInstance_Check(x)) {
  723.         PyObject *call = PyObject_GetAttrString(x, "__call__");
  724.         if (call == NULL) {
  725.             PyErr_Clear();
  726.             return 0;
  727.         }
  728.         /* Could test recursively but don't, for fear of endless
  729.            recursion if some joker sets self.__call__ = self */
  730.         Py_DECREF(call);
  731.         return 1;
  732.     }
  733.     return 0;
  734. }
  735.  
  736.  
  737. /*
  738. NoObject is usable as a non-NULL undefined value, used by the macro None.
  739. There is (and should be!) no way to create other objects of this type,
  740. so there is exactly one (which is indestructible, by the way).
  741. */
  742.  
  743. /* ARGSUSED */
  744. static PyObject *
  745. none_repr(op)
  746.     PyObject *op;
  747. {
  748.     return PyString_FromString("None");
  749. }
  750.  
  751. static PyTypeObject PyNothing_Type = {
  752.     PyObject_HEAD_INIT(&PyType_Type)
  753.     0,
  754.     "None",
  755.     0,
  756.     0,
  757.     0,        /*tp_dealloc*/ /*never called*/
  758.     0,        /*tp_print*/
  759.     0,        /*tp_getattr*/
  760.     0,        /*tp_setattr*/
  761.     0,        /*tp_compare*/
  762.     (reprfunc)none_repr, /*tp_repr*/
  763.     0,        /*tp_as_number*/
  764.     0,        /*tp_as_sequence*/
  765.     0,        /*tp_as_mapping*/
  766.     0,        /*tp_hash */
  767. };
  768.  
  769. PyObject _Py_NoneStruct = {
  770.     PyObject_HEAD_INIT(&PyNothing_Type)
  771. };
  772.  
  773.  
  774. #ifdef Py_TRACE_REFS
  775.  
  776. static PyObject refchain = {&refchain, &refchain};
  777.  
  778. void
  779. _Py_ResetReferences()
  780. {
  781.     refchain._ob_prev = refchain._ob_next = &refchain;
  782.     _Py_RefTotal = 0;
  783. }
  784.  
  785. void
  786. _Py_NewReference(op)
  787.     PyObject *op;
  788. {
  789.     _Py_RefTotal++;
  790.     op->ob_refcnt = 1;
  791.     op->_ob_next = refchain._ob_next;
  792.     op->_ob_prev = &refchain;
  793.     refchain._ob_next->_ob_prev = op;
  794.     refchain._ob_next = op;
  795. #ifdef COUNT_ALLOCS
  796.     inc_count(op->ob_type);
  797. #endif
  798. }
  799.  
  800. void
  801. _Py_ForgetReference(op)
  802.     register PyObject *op;
  803. {
  804. #ifdef SLOW_UNREF_CHECK
  805.         register PyObject *p;
  806. #endif
  807.     if (op->ob_refcnt < 0)
  808.         Py_FatalError("UNREF negative refcnt");
  809.     if (op == &refchain ||
  810.         op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
  811.         Py_FatalError("UNREF invalid object");
  812. #ifdef SLOW_UNREF_CHECK
  813.     for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
  814.         if (p == op)
  815.             break;
  816.     }
  817.     if (p == &refchain) /* Not found */
  818.         Py_FatalError("UNREF unknown object");
  819. #endif
  820.     op->_ob_next->_ob_prev = op->_ob_prev;
  821.     op->_ob_prev->_ob_next = op->_ob_next;
  822.     op->_ob_next = op->_ob_prev = NULL;
  823. #ifdef COUNT_ALLOCS
  824.     op->ob_type->tp_free++;
  825. #endif
  826. }
  827.  
  828. void
  829. _Py_Dealloc(op)
  830.     PyObject *op;
  831. {
  832.     destructor dealloc = op->ob_type->tp_dealloc;
  833.     _Py_ForgetReference(op);
  834.     if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL-1)
  835.         op->ob_type = NULL;
  836.     (*dealloc)(op);
  837. }
  838.  
  839. void
  840. _Py_PrintReferences(fp)
  841.     FILE *fp;
  842. {
  843.     PyObject *op;
  844.     fprintf(fp, "Remaining objects:\n");
  845.     for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
  846.         fprintf(fp, "[%d] ", op->ob_refcnt);
  847.         if (PyObject_Print(op, fp, 0) != 0)
  848.             PyErr_Clear();
  849.         putc('\n', fp);
  850.     }
  851. }
  852.  
  853. PyObject *
  854. _Py_GetObjects(self, args)
  855.     PyObject *self;
  856.     PyObject *args;
  857. {
  858.     int i, n;
  859.     PyObject *t = NULL;
  860.     PyObject *res, *op;
  861.  
  862.     if (!PyArg_ParseTuple(args, "i|O", &n, &t))
  863.         return NULL;
  864.     op = refchain._ob_next;
  865.     res = PyList_New(0);
  866.     if (res == NULL)
  867.         return NULL;
  868.     for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
  869.         while (op == self || op == args || op == res || op == t ||
  870.                t != NULL && op->ob_type != (PyTypeObject *) t) {
  871.             op = op->_ob_next;
  872.             if (op == &refchain)
  873.                 return res;
  874.         }
  875.         if (PyList_Append(res, op) < 0) {
  876.             Py_DECREF(res);
  877.             return NULL;
  878.         }
  879.         op = op->_ob_next;
  880.     }
  881.     return res;
  882. }
  883.  
  884. #endif
  885.  
  886.  
  887. /* Hack to force loading of cobject.o */
  888. PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
  889.  
  890.  
  891. /* Hack to force loading of abstract.o */
  892. int (*_Py_abstract_hack) Py_FPROTO((PyObject *)) = &PyObject_Length;
  893.  
  894.  
  895. /* Python's malloc wrappers (see mymalloc.h) */
  896.  
  897. ANY *
  898. PyMem_Malloc(nbytes)
  899.     size_t nbytes;
  900. {
  901. #if _PyMem_EXTRA > 0
  902.     if (nbytes == 0)
  903.         nbytes = _PyMem_EXTRA;
  904. #endif
  905.     return PyMem_MALLOC(nbytes);
  906. }
  907.  
  908. ANY *
  909. PyMem_Realloc(p, nbytes)
  910.     ANY *p;
  911.     size_t nbytes;
  912. {
  913. #if _PyMem_EXTRA > 0
  914.     if (nbytes == 0)
  915.         nbytes = _PyMem_EXTRA;
  916. #endif
  917.     return PyMem_REALLOC(p, nbytes);
  918. }
  919.  
  920. void
  921. PyMem_Free(p)
  922.     ANY *p;
  923. {
  924.     PyMem_FREE(p);
  925. }
  926.  
  927.  
  928. /* Python's object malloc wrappers (see objimpl.h) */
  929.  
  930. ANY *
  931. PyObject_Malloc(nbytes)
  932.     size_t nbytes;
  933. {
  934.     return PyObject_MALLOC(nbytes);
  935. }
  936.  
  937. ANY *
  938. PyObject_Realloc(p, nbytes)
  939.     ANY *p;
  940.     size_t nbytes;
  941. {
  942.     return PyObject_REALLOC(p, nbytes);
  943. }
  944.  
  945. void
  946. PyObject_Free(p)
  947.     ANY *p;
  948. {
  949.     PyObject_FREE(p);
  950. }
  951.  
  952.  
  953. /* These methods are used to control infinite recursion in repr, str, print,
  954.    etc.  Container objects that may recursively contain themselves,
  955.    e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
  956.    Py_ReprLeave() to avoid infinite recursion.
  957.  
  958.    Py_ReprEnter() returns 0 the first time it is called for a particular
  959.    object and 1 every time thereafter.  It returns -1 if an exception
  960.    occurred.  Py_ReprLeave() has no return value.
  961.  
  962.    See dictobject.c and listobject.c for examples of use.
  963. */
  964.  
  965. #define KEY "Py_Repr"
  966.  
  967. int
  968. Py_ReprEnter(obj)
  969.     PyObject *obj;
  970. {
  971.     PyObject *dict;
  972.     PyObject *list;
  973.     int i;
  974.  
  975.     dict = PyThreadState_GetDict();
  976.     if (dict == NULL)
  977.         return -1;
  978.     list = PyDict_GetItemString(dict, KEY);
  979.     if (list == NULL) {
  980.         list = PyList_New(0);
  981.         if (list == NULL)
  982.             return -1;
  983.         if (PyDict_SetItemString(dict, KEY, list) < 0)
  984.             return -1;
  985.         Py_DECREF(list);
  986.     }
  987.     i = PyList_GET_SIZE(list);
  988.     while (--i >= 0) {
  989.         if (PyList_GET_ITEM(list, i) == obj)
  990.             return 1;
  991.     }
  992.     PyList_Append(list, obj);
  993.     return 0;
  994. }
  995.  
  996. void
  997. Py_ReprLeave(obj)
  998.     PyObject *obj;
  999. {
  1000.     PyObject *dict;
  1001.     PyObject *list;
  1002.     int i;
  1003.  
  1004.     dict = PyThreadState_GetDict();
  1005.     if (dict == NULL)
  1006.         return;
  1007.     list = PyDict_GetItemString(dict, KEY);
  1008.     if (list == NULL || !PyList_Check(list))
  1009.         return;
  1010.     i = PyList_GET_SIZE(list);
  1011.     /* Count backwards because we always expect obj to be list[-1] */
  1012.     while (--i >= 0) {
  1013.         if (PyList_GET_ITEM(list, i) == obj) {
  1014.             PyList_SetSlice(list, i, i + 1, NULL);
  1015.             break;
  1016.         }
  1017.     }
  1018. }
  1019.  
  1020. /*
  1021.   trashcan
  1022.   CT 2k0130
  1023.   non-recursively destroy nested objects
  1024.  
  1025.   CT 2k0223
  1026.   everything is now done in a macro.
  1027.  
  1028.   CT 2k0305
  1029.   modified to use functions, after Tim Peter's suggestion.
  1030.  
  1031.   CT 2k0309
  1032.   modified to restore a possible error.
  1033.  
  1034.   CT 2k0325
  1035.   added better safe than sorry check for threadstate
  1036.  
  1037.   CT 2k0422
  1038.   complete rewrite. We now build a chain via ob_type
  1039.   and save the limited number of types in ob_refcnt.
  1040.   This is perfect since we don't need any memory.
  1041.   A patch for free-threading would need just a lock.
  1042. */
  1043.  
  1044. #define Py_TRASHCAN_TUPLE       1
  1045. #define Py_TRASHCAN_LIST        2
  1046. #define Py_TRASHCAN_DICT        3
  1047. #define Py_TRASHCAN_FRAME       4
  1048. #define Py_TRASHCAN_TRACEBACK   5
  1049. /* extend here if other objects want protection */
  1050.  
  1051. int _PyTrash_delete_nesting = 0;
  1052.  
  1053. PyObject * _PyTrash_delete_later = NULL;
  1054.  
  1055. void
  1056. _PyTrash_deposit_object(op)
  1057.     PyObject *op;
  1058. {
  1059.     int typecode;
  1060.     PyObject *hold = _PyTrash_delete_later;
  1061.  
  1062.     if (PyTuple_Check(op))
  1063.         typecode = Py_TRASHCAN_TUPLE;
  1064.     else if (PyList_Check(op))
  1065.         typecode = Py_TRASHCAN_LIST;
  1066.     else if (PyDict_Check(op))
  1067.         typecode = Py_TRASHCAN_DICT;
  1068.     else if (PyFrame_Check(op))
  1069.         typecode = Py_TRASHCAN_FRAME;
  1070.     else if (PyTraceBack_Check(op))
  1071.         typecode = Py_TRASHCAN_TRACEBACK;
  1072.     op->ob_refcnt = typecode;
  1073.  
  1074.     op->ob_type = (PyTypeObject*)_PyTrash_delete_later;
  1075.     _PyTrash_delete_later = op;
  1076. }
  1077.  
  1078. void
  1079. _PyTrash_destroy_chain()
  1080. {
  1081.     while (_PyTrash_delete_later) {
  1082.         PyObject *shredder = _PyTrash_delete_later;
  1083.         _PyTrash_delete_later = (PyObject*) shredder->ob_type;
  1084.  
  1085.         switch (shredder->ob_refcnt) {
  1086.         case Py_TRASHCAN_TUPLE:
  1087.             shredder->ob_type = &PyTuple_Type;
  1088.             break;
  1089.         case Py_TRASHCAN_LIST:
  1090.             shredder->ob_type = &PyList_Type;
  1091.             break;
  1092.         case Py_TRASHCAN_DICT:
  1093.             shredder->ob_type = &PyDict_Type;
  1094.             break;
  1095.         case Py_TRASHCAN_FRAME:
  1096.             shredder->ob_type = &PyFrame_Type;
  1097.             break;
  1098.         case Py_TRASHCAN_TRACEBACK:
  1099.             shredder->ob_type = &PyTraceBack_Type;
  1100.             break;
  1101.         }
  1102.         _Py_NewReference(shredder);
  1103.  
  1104.         ++_PyTrash_delete_nesting;
  1105.         Py_DECREF(shredder);
  1106.         --_PyTrash_delete_nesting;
  1107.     }
  1108. }
  1109.  
  1110.